﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Flower.Client;
using Flower.Services.Data;
using Flower.Workflow;
using Flower.Directory.Util;
using Flower.Processing.Interruptions;
using Process = Flower.Workflow.Process;

namespace Flower.Processing.Activities
{
    [SaveAfter]
    [Transactional]
    [Retry]
    public class ForEach<T> : Jump
    {
        private const string GET_MESSAGES_SCRIPT = "@GetMessages";

        internal Func<IContext, string> Subset { get; set; }
        internal Func<IContext, int> BatchSize { get; set; }
        internal Func<IContext, MessageProperty> OrderBy { get; set; }
        internal Func<IContext, Workflow.SortOrder> Order { get; set; }
        internal Func<IContext, bool> Wait { get; set; }
        internal Action<string, T> Item { get; set; } 

        internal ForEach() { }

        public override bool IsBlocking
        {
            get { return true; }
        }

        private static IEnumerable<Process.ForEachData.MessageInfo> GetMessages
        (
            Processor processor,
            string subset,
            int property,
            int order,
            long offset,
            long limit,
            string pid
        )
        {
            processor.Log.Trace(() => string.Format("Executing __getMessages({0}, {1}, {2}, {3}, {4}, {5}).", subset, property, order, offset, limit, pid));

            var script =
                processor
                    .Client
                    .CreateScript()
                    .SetText(GET_MESSAGES_SCRIPT)
                    .AddParameter("subset", subset)
                    .AddParameter("property", property)
                    .AddParameter("order", order)
                    .AddParameter("offset", offset)
                    .AddParameter("limit", limit);

            if (pid != null)
            {
                script.AddParameter("pid", pid);
            }

            var result =
                script
                    .Execute()
                    .Get<IList<DirectoryEntry>>("messages");

            return 
                (result != null) ? 
                result.Select(ent => 
                {
                    var msg = (Message)ent;

                    return new Process.ForEachData.MessageInfo
                    {
                        Id = msg.Id,
                        Name = msg.Name,
                        Data = (msg.Data != null) ? msg.Data.Data : null,
                        DataFormat = (msg.Data != null) ? (int)msg.Data.Format : 0
                    };
                }).ToList() :
                new List<Process.ForEachData.MessageInfo>();
        }

        public override Interruption Do(Processor processor)
        {
            Process.ForEachData data =
                processor.State.__ForEachData[processor.State.__ForEachData.Count - 1];

            if (data.Index == data.Batch.Count)
            {
                string subset = Subset(processor);
                
                if (subset == null) throw new ArgumentException("Subset is not specified.");

                subset = DirectoryUtil.LocalSubsetToGlobal(processor.Pid, subset);

                data.Offset -= data.RemovalsCount;
                data.RemovalsCount = 0;
                data.Index = 0;

                data.Batch.Clear();
                data.Batch.AddRange
                (
                    GetMessages
                    (
                        processor,
                        subset,
                        (int)OrderBy(processor),
                        (int)Order(processor),
                        data.Offset,
                        data.Offset + BatchSize(processor),
                        null
                    )
                );

                if (data.Batch.Count == 0)
                {
                    if (Wait(processor))
                    {
                        data.Batch.AddRange
                        (
                            GetMessages
                            (
                                processor,
                                subset,
                                (int)OrderBy(processor),
                                (int)Order(processor),
                                data.Offset,
                                data.Offset + BatchSize(processor),
                                processor.Pid
                            )
                        );

                        if (data.Batch.Count == 0)
                        {
                            return Waiting.Instance;
                        }
                    }
                    else
                    {
                        processor.State.__ActivityPointer = Position;
                        return null;
                    }
                }

                data.Offset += data.Batch.Count;
            }

            Process.ForEachData.MessageInfo msg = data.Batch[data.Index];
            ++data.Index;

            T item;

            if (msg.Data != null)
            {
                var msgBlob = new Blob
                {
                    Data = msg.Data,
                    Format = (BlobFormat)msg.DataFormat
                };

                item = msgBlob.To<T>();
            }
            else
            {
                item = default(T);
            }

            string itemName = msg.Name;

            Item(itemName, item);

            data.MessageId = msg.Id;

            ++processor.State.__ActivityPointer;
            return null;
        }
    }
}
